package cn.bdqn.commen;

import cn.bdqn.entity.SysLog;
import cn.bdqn.entity.SysUser;
import cn.bdqn.service.sys.SysJournalService;
import cn.bdqn.utils.IpUtiles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.Date;

/**
 * @ProjectName: ycbdqn
 * @Package: cn.bdqn.commen
 * @Author: huat
 * @Date: 2020/3/6 13:49
 * @Version: 1.0
 */
@Component
public class MyHttpSessionListener implements HttpSessionListener {
    @Autowired
    SysJournalService sysLogService;
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        //获取请求
        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes()).getRequest();
        SysUser sysUser=(SysUser) httpSessionEvent.getSession().getAttribute("user");
        SysLog sysLog=new SysLog();
        sysLog.setUsername(sysUser.getUsername());
        sysLog.setMethod("loginout");
        sysLog.setCreateDate(new Date());
        sysLog.setIp(IpUtiles.getRealIp(request));
        sysLog.setOperation("退出系统");

        sysLogService.saveSysLog(sysLog);
    }
}
